package com.xdxc.service.consumer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xdxc.mapper.ScoringTaskMapper;
import com.xdxc.model.entity.ScoringTask;
import com.xdxc.service.serviceinterface.ScoringTaskService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Component
@Slf4j
@RocketMQMessageListener(
        topic = "exam_scoring_topic",
        consumerGroup = "exam_scoring_consumer_group",
        selectorExpression = "*"
)
public class ExamScoringConsumer implements RocketMQListener<Map<String, Object>> {


    @Autowired
    private ScoringTaskService scoringTaskService;

    @Override
    public void onMessage(Map<String, Object> message) {
        Long examId = Long.valueOf(message.get("examId").toString());
        String examName = message.get("examName").toString();
        // 1. 获取任务并标记为处理中
        ScoringTask task = scoringTaskService.getOne(new LambdaQueryWrapper<ScoringTask>().eq(ScoringTask::getExamId,examId));
        if (task != null ) {
            log.warn("无效或已处理的评分任务，任务ID: {}", examId);
            return;
        }
        try {
            // 2. 获取考试相关信息
            task.setExamId(examId);
            task.setExamName(examName);
            task.setIsEnd(0);
            scoringTaskService.save(task);
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }


}